package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import model.domain.Admin;
import model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Map login(Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");

        String key = Constants.CAP_CODE + uuid;
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code)||!verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(key);

        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getUsername, username);
        Admin admin = adminMapper.selectOne(adminLambdaQueryWrapper);

        password = SecureUtil.md5(password);
        if (admin == null || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或密码错误");
        }

        HashMap<String, Object> claim = new HashMap<>();
        claim.put("id", admin.getId());
        claim.put("username", username);
        String token = JwtUtils.getToken(claim);

        Map res = new HashMap<>();
        res.put("token", token);

        return res;
    }

    public AdminVo profile() {
        Long id = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(id);
        return AdminVo.init(admin);
    }
}
